package com.estar.integaration.Controller;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.estar.integaration.Mapper.CartGoodsMapper;
import com.estar.integaration.Service.*;
import com.estar.integaration.Util.MaterialUtil;
import com.estar.integaration.Util.Util;
import com.estar.integaration.entity.Cart;
import com.estar.integaration.entity.CartGoods;
import com.estar.integaration.entity.Material;
import com.estar.integaration.entity.NoSQL.Res;
import com.estar.integaration.entity.User;
import com.google.gson.Gson;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 购物车
 */
@RestController
@RequestMapping("/cart-goods")
public class CartGoodsController {
    @Autowired
    ICartGoodsService iCartGoodsService;
    @Autowired
    IMaterialService iMaterialService ;
    @Autowired
    IUserService iUserService;
    @Autowired
    IOperationHistoryService iOperationHistoryService;
    @Autowired
    ICartService cartService;


    Logger logger = LoggerFactory.getLogger(ProductionScheduleController.class);
    //用户绑定的购物车 <userName,cart>
    HashMap<String, Cart> cartHashMap = new HashMap<>();
    List<Material> materialCartList = new ArrayList<>();//购物车
    List<Material> materialList = new ArrayList<>();
    @Value("${spring.profiles.active}")
    private String mEnvironment;
    Date date = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String currentdate = sdf.format(date);
    Timestamp timestamp = Timestamp.valueOf(currentdate);
    /**
     * 功能： 加入购物车
     * @param buyJson
     */
    @PostMapping("/buyMaterial")
    public Res clickBuy(@RequestBody JSONObject buyJson) throws CloneNotSupportedException {

        String userName = buyJson.getString("userName");

        JSONArray simpleJsonArray = buyJson.getJSONArray("buyArrSimple");

        //查出用户名对应的user

        User user = iUserService.findByUserName(userName);

//        Cart cart = cartService.findCartByUserid(user.getId());

        Cart cart = cartHashMap.get(userName);

        if(cart == null){

            cart = cartService.findCartByUserId(user.getId());

            if(cart == null){

                cart = new Cart(Util.getUUID(),user.getId());

                cartHashMap.put(userName,cart);

                cartService.insert(cart);

            }

        }

        //buySimpleArray解析
        List<CartGoods> tmpCartGList = new ArrayList<>();List<Material> tmpPurchaseList = new ArrayList<>();//用于批量插入

        for(int j = 0; j < simpleJsonArray.size() ;j++){

            JSONObject tempJson = simpleJsonArray.getJSONObject(j);

            String materialId = tempJson.getString("id"); //物料id

            Double buyNum = tempJson.get("buy_num") == null ? null : tempJson.getDouble("buy_num") ;

            Double backNum = tempJson.get("back_num") == null ? null : tempJson.getDouble("back_num");

            String productId = tempJson.getString("productId");

            String CartId = cart.getId();

            tmpCartGList.add(new CartGoods(Util.getUUID(),materialId,CartId,buyNum,backNum,productId));

            tmpPurchaseList.add(updatePurchaseDepartBuyandNoBuyandBackNum(materialId,buyNum,backNum));

        }

        //插入
        iCartGoodsService.saveBatch(tmpCartGList);

        //update
        iMaterialService.updateBatchById(tmpPurchaseList);

        tmpCartGList.clear();

        return new Res("20000","success");

    }

    /**
     * 功能： 查看我的购物车
     */
    @GetMapping("/getMyCart")
    public Res getCart(@RequestParam String userName){
        User user = iUserService.findByUserName(userName);
        Cart cart = cartService.findCartByUserId(user.getId()); //找到该用户的cart
        if(cart == null){
            return new Res("40000","还未登录，请重新登录使用");
        }
        List<CartGoods> cartGoodList = iCartGoodsService.getcartGoodsBycartId(cart.getId());
        List<Material> returnDepartureList = updatePurchase(cartGoodList);
        return new Res("20000",new Gson().toJson(returnDepartureList));

    }

    /**
     * 清空购物车
     * @param userName
     * @return
     */
    @GetMapping("/clearCart")
    public Res clearCart(@RequestParam String userName){
        //用于update一个清空购物车的Batch
        List<Material> tmpMaterialList = new ArrayList<>();
        Cart cart = cartHashMap.get(userName);
        if(cart == null){

            User user = iUserService.findByUserName(userName);

            cart = cartService.findCartByUserId(user.getId());

            if(cart == null){

                return new Res("40000","未找到购物车，请重新登陆");

            }
        }

        List<CartGoods> cartGoodsList = iCartGoodsService.getcartGoodsBycartId(cart.getId());
        for(CartGoods cG : cartGoodsList){
            iMaterialService.updateById(
                    updateClearCartPurchaseDepartBuyandNoBuyandBackNum(
                            cG.getMaterialId(),cG.getThisBuy(),cG.getThisBack()));
        }
        iCartGoodsService.clearMyCartByCartId(cart.getId());
        materialList = iMaterialService.selectList(null);
        logger.info(userName+"清空了购物车");
        return new Res("20000",new Gson().toJson(
                MaterialUtil.filterListUnpurchasedBiggerThanZero(
                        materialList)));
    }
    /**
     * 导出本次购买了的内容
     * 购买并导出
     * @return
     * @throws IOException
     */
    @GetMapping("/getPurchaseExcel")
    public ResponseEntity<FileSystemResource> getExcelFile(@RequestParam String userName) throws IOException {

        String filePath = "";
        if(mEnvironment.equals("dev")){
            filePath = "D:\\SCM_file\\purchaseProcess\\test\\purchase.xls";
        }else if(mEnvironment.equals("prod") || mEnvironment.equals("prodB")){
            filePath = "/" + "root" + "/" + "excel" + "/" +"purchase.xls";
        }

        //写Excel到本地
        File file =  null;

        HSSFWorkbook workbook = new HSSFWorkbook();

        HSSFSheet sheet = workbook.createSheet();

        HSSFRow headRow = sheet.createRow(0);

        createHeadRow(headRow);

        //拿到User
        User user = iUserService.findByUserName(userName);

        HashMap<String,Double> needBuyHash = iCartGoodsService.getAllMaterialDepartNeedBuyByCartId(user.getId()); //这些id要买

        int line = 1;

        List<Material> purchaseBatchSQLList = new ArrayList<>();

        for(Map.Entry<String,Double> materialAndquan : needBuyHash.entrySet()){

            String materialId = materialAndquan.getKey();

            Double needBuy = materialAndquan.getValue();

            //更新原表
//            Material material = selectPurById(materialId);
             Material material =  iMaterialService.selectPurById(materialId);


//      purchaseBatchSQLList.add(updatePurchaseDepartafterBuy(purchasedepart,needBuy));

            //写出excel
            HSSFRow row = sheet.createRow(line);

            createCellinline(row,needBuy,material);

            line++;

        }

        iMaterialService.updateBatchById(purchaseBatchSQLList);

        purchaseBatchSQLList.clear();

        //清空我的购物车

        if(user == null)
            return null;

        String cartId = cartService.findCartByUserId(user.getId()).getId();

        iCartGoodsService.clearMyCartByCartId(cartId);

        workbook.setSheetName(0,"sheet1");

        //全部写完

        logger.info("getPurchaseExcel ==============================开始输出文件" + filePath);

        FileOutputStream fileOutputStream = new FileOutputStream(filePath);

        workbook.write(fileOutputStream);

        fileOutputStream.close();

        file = new File(filePath);

        materialCartList.clear();//清除购物车

        if(file.exists()){

            return Util.exportExcel(file);

        }

        return null;
    }
    /**
     * 更新点击"加入购物车"之后purchaseDepart记录的数据
     * @param
     */
    private Material updatePurchaseDepartBuyandNoBuyandBackNum(String id,Double buy_num,Double back_num){

        Material material = iMaterialService.getById(id);


        if(buy_num != null){

            material.setPurchased(material.getPurchased() + buy_num); //已购+本次购买

            material.setUnpurchased(material.getUnpurchased() - buy_num); //需购-本次购买

        }

        if(back_num != null){

            material.setPurchased(material.getPurchased() - back_num); //已购-退货

            material.setUnpurchased(material.getUnpurchased() + back_num);//需购+退货

            if(material.getBackGoods() == null){
                material.setBackGoods(back_num); //退货 = 之前的退货数量 + 本次的退货数量
            }
            if(material.getBackGoods() != null){
                material.setBackGoods(material.getBackGoods() + back_num);
            };
        }

        return material;

    }
    /**
     * 更新点击"清空购物车"之后purchaseDepart记录的数据(反向操作)
     * @param
     */
    private Material updateClearCartPurchaseDepartBuyandNoBuyandBackNum(String id,Double buy_num,Double back_num){

        Material material = iMaterialService.getById(id);

        if(buy_num != null){

            material.setPurchased(material.getPurchased() - buy_num); //已购-本次购买

            material.setUnpurchased(material.getUnpurchased() + buy_num); //需购+本次购买

        }


        if(back_num != null){

            material.setPurchased(material.getPurchased() + back_num); //已购+退货

            material.setUnpurchased(material.getUnpurchased() - back_num);//需购-退货

            if(material.getBackGoods()==null){

                material.setBackGoods(0-back_num);//退货=SQL退货 -本要退的货
            }
            if(material.getBackGoods()!=null){

                material.setBackGoods(material.getBackGoods()-back_num);//退货=SQL退货 -本要退的货

            }

        }



        return material;

    }
    /**
     * 更新并且返回更新的purchase
     * @return
     */
    private List<Material> updatePurchase(List<CartGoods> cartGoodList){
        List<Material> materialList = new ArrayList<>();
        for(CartGoods c : cartGoodList){
            Material p = iMaterialService.selectPurById(c.getMaterialId());
            if(p == null)
                continue;
            p.setPurchased(null);
            p.setUnpurchased(null);
            p.setThisPurchase(c.getThisBuy());
            p.setBackGoods(c.getThisBack());
            materialList.add(p);
        }
        return materialList;
    }

    /**
     * 返回一个商品id对应要买的个数
     * @param userId
     * @return
     */
    public HashMap<String,Double> getAllMaterialDepartNeedBuyByCartId(String userId){
        String cardId = cartService.findCartByUserId(userId).getId();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("cart_id",cardId);
        List<CartGoods> cartGoodList =  cartService.selectList(queryWrapper);//找到购物车里面属于用户的物料
        //返回物料购买情况 <物料id,个数>
        HashMap<String,Double> buyMaterialQuantity = new HashMap<>();
        for(int j = 0 ; j < cartGoodList.size(); j++){
            CartGoods cartGoods = cartGoodList.get(j);
            if(buyMaterialQuantity.containsKey(cartGoods.getMaterialId())){//如果有多个则合并
                Double oldNum = buyMaterialQuantity.get(cartGoods.getMaterialId());
                Double newNum = cartGoods.getThisBuy() + oldNum;
                buyMaterialQuantity.put(cartGoods.getMaterialId(),newNum);
            }else {
                buyMaterialQuantity.put(cartGoods.getMaterialId(),cartGoods.getThisBuy());
            }
        }
        return buyMaterialQuantity;
    }


    /**
     * 创建第一行 头
     * @param headRow
     */
    private void createHeadRow(HSSFRow headRow){
        //顺序更改
        headRow.createCell(0).setCellValue("物料编码");
        headRow.createCell(1).setCellValue("品名");
        headRow.createCell(2).setCellValue("规格");
        headRow.createCell(3).setCellValue("品牌");
        headRow.createCell(4).setCellValue("备注");
        headRow.createCell(5).setCellValue("需购买");
        headRow.createCell(6).setCellValue("本次购买");
        headRow.createCell(7).setCellValue("退货数量");
        headRow.createCell(8).setCellValue("采购交期");
        headRow.createCell(9).setCellValue("机台号");
    }

    /**
     * 创建数据行
     * @param needBuy
     */
    private void createCellinline(HSSFRow row,Double needBuy,Material material){
        //物料编码
        row.createCell(0).setCellValue(material.getMaterialNo());

        //品名
        row.createCell(1).setCellValue(material.getMaterialName());

        //规格
        row.createCell(2).setCellValue(material.getSpecs());

        //品牌
        row.createCell(3).setCellValue(material.getBrand());

        //备注
        row.createCell(4).setCellValue(material.getBomRemark());

        //需购
        row.createCell(5).setCellValue(material.getUnpurchased());

        //本次购买
        row.createCell(6).setCellValue(needBuy == null ? 0 : needBuy);

        //退货数量
        row.createCell(7).setCellValue(material.getBackGoods() == null ? 0 : material.getBackGoods());

        if(material.getDelivery() == null){
            setEmptyDeliveryMaterialDelivery(material);
        }

        String delivery = new SimpleDateFormat("yyyy-MM-dd").format(material.getDelivery());



        //采购交期
        row.createCell(8).setCellValue(delivery);

        //机台号
        row.createCell(9).setCellValue(material.getACode());

    }

    private void setEmptyDeliveryMaterialDelivery(Material material){
        Date date = new Date();
        material.setDelivery(date);
    }

}
